<?php
/**
 * Created by PhpStorm.
 * User: liugang
 * Date: 2019-03-21
 * Time: 16:45
 */

namespace App\Http\Controllers\Api\V1;


use App\Http\Controllers\Api\ApiController;
use App\Library\Common;
use App\Models\Driver;
use App\Models\Member;
use App\Models\MemberAudit;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Validator;

/**
 * 司机用户相关
 * Class DriversController
 * @package App\Http\Controllers\Api\V1
 */
class DriversController extends ApiController
{
    /**
     * 获取司机个人资料接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDriverProfile(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'driver_uuid' => 'required|size:36',
            ]);

            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $driverUuid = $request->get('driver_uuid');
            $oDriver    = Member::with(['driver', 'audit'])->where('uuid', $driverUuid)->firstOrFail();
            $driverInfo = $oDriver->toArray();

            $data['avatar']       = $driverInfo['avatar'] ?? '';
            $data['name']         = $driverInfo['name'] ?? '';
            $data['phone']        = $driverInfo['phone'] ?? '';
            $data['car_no']       = $driverInfo['driver']['car_no'] ?? '';
            $data['card_no']      = $driverInfo['driver']['card_no'] ?? '';
            $data['status']       = $driverInfo['driver']['status'] ?? 0;
            $data['audit_status'] = $driverInfo['audit']['audit_status'] ?? 0;
            $data['audit_des']    = $driverInfo['audit']['audit_des'] ?? '';

            return $this->success('success', $data);
        } catch (ModelNotFoundException $e) {
            return $this->error(Common::notFoundModelFormat($e->getModel()));
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 空车上报或非空车上报
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function broadcastCarStatus(Request $request)
    {
        try {

            $validator = Validator::make($request->all(), [
                'driver_uuid' => 'required|size:36',
                'car_status'  => 'required'
            ]);

            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $driverUuid = $request->get('driver_uuid');
            $carStatus  = intval($request->get('car_status'));

            $oDriver = Driver::where('uuid', $driverUuid)->first();
            if (is_null($oDriver)) {
                throw new \Exception('没有找到司机数据');
            }

            if (!in_array($carStatus, [Driver::$carStatusAvailable, Driver::$carStatusOccupied])) {
                throw new \Exception('非法车辆状态码');
            }

            $oDriver->car_status = $carStatus;
            $oDriver->save();

            return $this->success('操作成功');

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 身份认证
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function identityVerify(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'driver_uuid'        => 'required|size:36',
                'name'               => 'required',
                'card_no'            => 'required|min:16|max:18',
                'pic_card_front'     => 'required',
                'pic_card_back'      => 'required',
                'pic_driver_license' => 'required',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
            $driverUuid = $request->get('driver_uuid');

            $user = Member::with('driver')
                ->where('uuid', $driverUuid)
                ->firstOrFail();

            // @step1: 更新v_drivers表
            $status = $user->driver->status;
            if ($user->driver->status == Driver::$statusUnverified) {
                $status = Driver::$statusIdentityVerified;
            } else if ($user->driver->status == Driver::$statusCarVerified) {
                $status = Driver::$statusVerified;
            }
            $user->driver->status             = $status;
            $user->driver->card_no            = $request->get('card_no');
            $user->driver->pic_card_front     = $request->get('pic_card_front');
            $user->driver->pic_card_back      = $request->get('pic_card_back');
            $user->driver->pic_driver_license = $request->get('pic_driver_license');
            $user->driver->save();

            // @step2：更新v_members表
            $user->name = $request->get('name');
            $user->save();

            // @step3: 更新审核状态
            $this->upAuditStatus($driverUuid);

            return $this->success('身份认证成功');
        } catch (ModelNotFoundException $e) {
            return $this->error(Common::notFoundModelFormat($e->getModel()));
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 车辆认证
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function carVerify(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'driver_uuid'     => 'required|size:36',
                'car_no'          => 'required', // 车牌号
                'pic_car_license' => 'required', // 行车证
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
            $driverUuid = $request->get('driver_uuid');

            $user = Driver::where('uuid', $driverUuid)->firstOrFail();

            // 更新司机认证信息
            $status = $user->status;
            if ($user->status == Driver::$statusUnverified) {
                $status = Driver::$statusCarVerified;
            } else if ($user->status == Driver::$statusIdentityVerified) {
                $status = Driver::$statusVerified;
            }
            $user->status          = $status;
            $user->car_no          = $request->get('car_no');
            $user->pic_car_license = $request->get('pic_car_license');
            $user->save();

            // 更新审核状态
            $this->upAuditStatus($driverUuid);

            return $this->success('车辆认证成功');
        } catch (ModelNotFoundException $e) {
            return $this->error(Common::notFoundModelFormat($e->getModel()));
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 新增或者更新司机认证 审核信息
     * @param $uuid 用户唯一标识
     * @return bool
     */
    protected function upAuditStatus($uuid)
    {
        $driver = Driver::onWriteConnection()->where('uuid', $uuid)->first();
        if ($driver->status == Driver::$statusVerified) {
            $auditInfo = MemberAudit::onWriteConnection()->where('uuid', $uuid)->first();
            if (empty($auditInfo)) {
                // 新建审核信息
                MemberAudit::create([
                    'member_id'    => $driver->member_id,
                    'uuid'         => $uuid,
                    'audit_status' => MemberAudit::STATUS_WAIT,
                ]);
            } else if ($auditInfo->audit_status == MemberAudit::STATUS_NO_PASS) {
                // 更新审核状态
                $auditInfo->audit_status = MemberAudit::STATUS_WAIT;
                $auditInfo->save();
            }
        }

        return true;
    }

    /**
     * 获取司机认证信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getVerifyInfo(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'driver_uuid' => 'required|size:36',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $user = Member::query()
                ->with(['driver', 'audit'])
                ->where('v_members.uuid', $request->get('driver_uuid'))
                ->firstOrFail();
            $data = [
                'uuid'               => $user->uuid,
                'name'               => $user->name ?? '',
                'phone'              => $user->phone ?? '',
                'card_no'            => $user->driver->card_no ?? '',
                'pic_card_front'     => $user->driver->pic_card_front ?? '',
                'pic_card_back'      => $user->driver->pic_card_back ?? '',
                'pic_driver_license' => $user->driver->pic_driver_license ?? '',
                'car_no'             => $user->driver->car_no ?? '',
                'pic_car_license'    => $user->driver->pic_car_license ?? '',
                'status'             => $user->driver->status ?? 0,
                'audit_status'       => $user->audit->audit_status ?? 0,
                'audit_des'          => $user->audit->audit_des ?? '',
            ];

            return $this->success('success', $data);
        } catch (ModelNotFoundException $e) {
            return $this->error(Common::notFoundModelFormat($e->getModel()));
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

}